package com.wsoft.hr.pm.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.wsoft.constant.CommonConstant;
import com.wsoft.core.service.CommonFreemarkerService;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.vo.MemberVO;
import com.wsoft.hr.pm.entity.HrPmWarningEntity;
import com.wsoft.hr.pm.entity.sys.HrMemberOrgRelationEntity;
import com.wsoft.hr.pm.enums.WarningTypeEnum;
import com.wsoft.hr.pm.manager.HrMemberOrgRelationManager;
import com.wsoft.hr.pm.manager.HrPmWarningManager;
import com.wsoft.hr.pm.mapper.HrPmWarningMapper;
import com.wsoft.hr.pm.vo.warning.ProgressLagWarningVO;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 进度滞后预警 job
 *
 * @Author z001
 * @Date 2025/3/7 10:09
 */
@Service
public class ProgressLagJob implements Job {

    @Resource
    private HrPmWarningMapper warningMapper;
    @Resource
    private HrPmWarningManager warningManager;
    @Resource
    private HrMemberOrgRelationManager relationManager;
    @Resource
    private CommonMemberService memberService;
    @Resource
    private CommonFreemarkerService freemarkerService;

    /**
     * 模版code
     */
    private final String FREEMARKER_CODE = "freemarker_code";
    /**
     * 百分比
     */
    private final String PERCENT = "percent";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail job = jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = job.getJobDataMap();

        //任务参数
        Object jobParam = jobDataMap.get(CommonConstant.JOB_PARAMS);
        if (ObjUtil.isNull(jobParam)) {
            return;
        }
        JSONObject param = JSONObject.parseObject(jobParam.toString());
        Object freemarkerCode = param.get(FREEMARKER_CODE);
        Object percent = null == param.get(PERCENT) ? "0.8" : param.get(PERCENT);
        if (null == freemarkerCode) {
            return;
        }

        //最后一次执行时间
        String lastExecuteTime = null == jobDataMap.get(CommonConstant.LAST_EXECUTE_TIME) ? null : jobDataMap.get(CommonConstant.LAST_EXECUTE_TIME).toString();
        //当前时间
        String nowExecuteTime = null == jobDataMap.get(CommonConstant.NOW_EXECUTE_TIME) ? null : jobDataMap.get(CommonConstant.NOW_EXECUTE_TIME).toString();

        List<ProgressLagWarningVO> progressLagWarningVoS = warningMapper.selectProgressLag(nowExecuteTime, lastExecuteTime, percent.toString());
        if(CollUtil.isEmpty(progressLagWarningVoS)){
            return;
        }
        List<Long> memberIds = progressLagWarningVoS.stream().map(ProgressLagWarningVO::getMemberId).collect(Collectors.toList());
        List<HrMemberOrgRelationEntity> relationList = relationManager.getByMemberIsd(memberIds);
        Map<Long, Long> relationMap = relationList.stream().collect(Collectors.toMap(HrMemberOrgRelationEntity::getMemberId ,HrMemberOrgRelationEntity::getHrOrgId));

        List<HrPmWarningEntity> warningList = new ArrayList<>();
        for (ProgressLagWarningVO vo : progressLagWarningVoS) {

            HrPmWarningEntity warning = new HrPmWarningEntity();
            warning.setTitle(buildFreemarkerMap(vo,percent,freemarkerCode));
            warning.setType(WarningTypeEnum.PROGRESS_LAG.getType());
            warning.setHrOrgId(relationMap.get(vo.getMemberId()));
            warning.setOpenType("component");
            warning.setOpenPage("");
            warningList.add(warning);
        }
        warningManager.saveBatch(warningList);
    }

    /**
     * 构建freemarker模板
     * @param vo
     * @param percent
     * @param freemarkerCode
     * @return
     */
    private String buildFreemarkerMap(ProgressLagWarningVO vo, Object percent,Object freemarkerCode){
        MemberVO memberVO = memberService.getMemberInfo(vo.getMemberId());
        Map<String,Object> map = new HashMap<>(3);
        map.put("memberName",memberVO.getName());
        map.put("templateName",vo.getTemplateName());
        map.put("percent",new BigDecimal(percent.toString()).multiply(new BigDecimal(100))+"%");
        //${memberName}${templateName}有指标完成度低于${percent}，请及时关注。
        return freemarkerService.sendTextTemplate(freemarkerCode.toString(), map,true);
    }
}
